package com.duoduo.commonn.redis.handle;


import com.duoduo.common.api.constants.Constant;
import com.duoduo.common.api.help.SpringContextInnerUtil;
import com.duoduo.common.api.myinterface.tracer.RedisTracer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class TraceHandler<T> implements MethodInterceptor {
	
	// 如果有链路跟踪
	private RedisTracer tracer;
	
	public TraceHandler(RedisTracer tracer){
		this.tracer = tracer;
	}

	@Override
	public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
		if(SpringContextInnerUtil.containsBean(Constant.TRACER_BEANNAME) && tracer != null){
			tracer.invoke(method.getName(), args);
		}
		Object result = null;
		Throwable th = null;
		try {
			result = proxy.invokeSuper(obj, args);
			return result;
		} catch (Throwable t) {
			th = t;
            throw t;
        } finally {
        	// 如果有链路跟踪
			if(SpringContextInnerUtil.containsBean(Constant.TRACER_BEANNAME) && tracer != null){
				tracer.invokeAfterClient(result, th);
			}
        }
	}

}
